#!/usr/bin/env python

__doc__ = """
xpathAppendFromFile
===================

:Authors: Karl Norby
:Version: 1.0
:Date: Sept. 5th, 2007

Deletes all tags found that matches a given XPath expression in an xml file.

Arguments
---------

1. xpath epxression
2. xml block file
3. *optional* filename (from stdin)
4. *optional* output (goes to stdout by default)

"""

import lxml.etree as ET
import os, sys
from StringIO import StringIO

def xsltTransform(xsltFile, xmlInput, xmlOutput=None):
    xsltDoc   = ET.parse(xsltFile)
    transform = ET.XSLT(xsltDoc)
    tree      = ET.parse(xmlInput)
    resTree   = transform(tree)
    retval = ET.tostring(resTree, pretty_print=True)
    if xmlOutput==None:
        return retval
    print >> xmlOutput, retval


def main():
    argc = len(sys.argv)
    if argc<2 or argc>4:
        raise "error: Wrong number of arguments"

    xsltFile = sys.argv[1]
    
    if argc==3 or argc==4:
        filename = sys.argv[2]
        if not os.path.isfile(filename):
            raise IOError, "%s is not a file" % filename
    else:
        filename = sys.stdin
    
    if argc==4:
        output = sys.argv[3]
        output = open(output, "w")
    else:
        output = sys.stdout

    xsltTransform(xsltFile, filename, output)
    sys.exit(0)

if __name__=="__main__":
    main()
